package cookies;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CookiesTest01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理字符乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        // 设置访问形式
        resp.setContentType("text/html;charset=utf-8");

        Cookie[] cookies = req.getCookies();
        System.out.println(cookies);
        // 判断用户是否是第一次得到cookies
        if (cookies!=null&&cookies.length!=0){
            for (Cookie cookie:cookies){
                String name=cookie.getName();
                if(name.equals("lastAccessTime")){
                    Date date = new Date();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String value=simpleDateFormat.format(date);
                    value= URLEncoder.encode(value,"utf-8");
                    cookie.setValue(value);
                    cookie.setMaxAge(60*60);
                    resp.addCookie(cookie);
                    resp.getWriter().println("欢迎回来！你上次访问的时间是："+URLEncoder.encode(cookie.getValue(),"utf-8"));
                    break;
                }
            }
        }else {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String value=simpleDateFormat.format(date);
            value= URLEncoder.encode(value,"utf-8");
            Cookie cookie = new Cookie("lastAccessTime", value);
            cookie.setMaxAge(60*60);
            resp.addCookie(cookie);
            resp.getWriter().println("这是您第一次访问本站");

        }
        //用户访问过之后重新设置用户的访问时间，存储到cookie中，然后发送到客户端浏览器
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
